import { Request, Response } from 'express';
import { PrismaClient, TimePeriod } from '@prisma/client';
import { ResponseHelper } from '../utils/response';

const prisma = new PrismaClient();

/**
 * 拥堵程度请求体接口
 */
interface CongestionLevelBody {
  timePeriod: TimePeriod;
  level: number;
}

/**
 * 批量更新拥堵程度请求体接口
 */
interface BatchCongestionBody {
  congestions: CongestionLevelBody[];
}

/**
 * 获取地点的拥堵程度
 * GET /api/v1/locations/:id/congestion
 */
export const getLocationCongestion = async (req: Request, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    const locationId = parseInt(id, 10);

    if (isNaN(locationId)) {
      ResponseHelper.validationError(res, [
        { field: 'id', message: '无效的地点ID' }
      ]);
      return;
    }

    // 检查地点是否存在
    const location = await prisma.location.findUnique({
      where: { id: locationId }
    });

    if (!location) {
      ResponseHelper.notFound(res, '地点不存在');
      return;
    }

    // 获取拥堵程度列表
    const congestions = await prisma.congestionLevel.findMany({
      where: { locationId },
      orderBy: {
        timePeriod: 'asc'
      }
    });

    ResponseHelper.success(res, congestions, '获取成功');

  } catch (error: any) {
    console.error('获取拥堵程度失败:', error);
    ResponseHelper.serverError(res, '获取拥堵程度失败', error);
  }
};

/**
 * 更新地点的拥堵程度（单个时段）
 * PUT /api/v1/locations/:id/congestion
 * 需要JWT认证
 */
export const updateCongestionLevel = async (req: Request, res: Response): Promise<void> => {
  try {
    if (!req.user) {
      ResponseHelper.unauthorized(res, '请先登录');
      return;
    }

    const { id } = req.params;
    const locationId = parseInt(id, 10);

    if (isNaN(locationId)) {
      ResponseHelper.validationError(res, [
        { field: 'id', message: '无效的地点ID' }
      ]);
      return;
    }

    const { timePeriod, level } = req.body as CongestionLevelBody;

    // 验证必填参数
    if (!timePeriod || level === undefined) {
      ResponseHelper.validationError(res, [
        ...(!timePeriod ? [{ field: 'timePeriod', message: '时段不能为空' }] : []),
        ...(level === undefined ? [{ field: 'level', message: '拥堵程度不能为空' }] : [])
      ]);
      return;
    }

    // 验证时段
    if (!['BREAKFAST', 'LUNCH', 'DINNER', 'OTHER'].includes(timePeriod)) {
      ResponseHelper.validationError(res, [
        { field: 'timePeriod', message: '时段必须是 BREAKFAST、LUNCH、DINNER 或 OTHER' }
      ]);
      return;
    }

    // 验证拥堵程度
    if (typeof level !== 'number' || level < 1 || level > 5) {
      ResponseHelper.validationError(res, [
        { field: 'level', message: '拥堵程度必须是1-5之间的整数' }
      ]);
      return;
    }

    // 检查地点是否存在且已审核通过
    const location = await prisma.location.findUnique({
      where: { id: locationId }
    });

    if (!location) {
      ResponseHelper.notFound(res, '地点不存在');
      return;
    }

    if (location.status !== 'APPROVED') {
      ResponseHelper.error(res, '该地点暂未通过审核，无法更新拥堵程度', 400);
      return;
    }

    // 使用upsert创建或更新拥堵程度
    const congestion = await prisma.congestionLevel.upsert({
      where: {
        locationId_timePeriod: {
          locationId,
          timePeriod
        }
      },
      update: {
        level
      },
      create: {
        locationId,
        timePeriod,
        level
      }
    });

    ResponseHelper.success(res, congestion, '更新成功');

  } catch (error: any) {
    console.error('更新拥堵程度失败:', error);
    ResponseHelper.serverError(res, '更新拥堵程度失败', error);
  }
};

/**
 * 批量更新地点的拥堵程度
 * PUT /api/v1/locations/:id/congestion/batch
 * 需要JWT认证
 */
export const batchUpdateCongestion = async (req: Request, res: Response): Promise<void> => {
  try {
    if (!req.user) {
      ResponseHelper.unauthorized(res, '请先登录');
      return;
    }

    const { id } = req.params;
    const locationId = parseInt(id, 10);

    if (isNaN(locationId)) {
      ResponseHelper.validationError(res, [
        { field: 'id', message: '无效的地点ID' }
      ]);
      return;
    }

    const { congestions } = req.body as BatchCongestionBody;

    // 验证必填参数
    if (!congestions || !Array.isArray(congestions) || congestions.length === 0) {
      ResponseHelper.validationError(res, [
        { field: 'congestions', message: '拥堵程度数据不能为空' }
      ]);
      return;
    }

    // 验证每个拥堵程度数据
    for (const cong of congestions) {
      if (!cong.timePeriod || cong.level === undefined) {
        ResponseHelper.validationError(res, [
          { field: 'congestions', message: '每个拥堵程度数据必须包含 timePeriod 和 level' }
        ]);
        return;
      }

      if (!['BREAKFAST', 'LUNCH', 'DINNER', 'OTHER'].includes(cong.timePeriod)) {
        ResponseHelper.validationError(res, [
          { field: 'timePeriod', message: '时段必须是 BREAKFAST、LUNCH、DINNER 或 OTHER' }
        ]);
        return;
      }

      if (typeof cong.level !== 'number' || cong.level < 1 || cong.level > 5) {
        ResponseHelper.validationError(res, [
          { field: 'level', message: '拥堵程度必须是1-5之间的整数' }
        ]);
        return;
      }
    }

    // 检查地点是否存在且已审核通过
    const location = await prisma.location.findUnique({
      where: { id: locationId }
    });

    if (!location) {
      ResponseHelper.notFound(res, '地点不存在');
      return;
    }

    if (location.status !== 'APPROVED') {
      ResponseHelper.error(res, '该地点暂未通过审核，无法更新拥堵程度', 400);
      return;
    }

    // 批量更新拥堵程度
    const results = await Promise.all(
      congestions.map(({ timePeriod, level }) =>
        prisma.congestionLevel.upsert({
          where: {
            locationId_timePeriod: {
              locationId,
              timePeriod
            }
          },
          update: { level },
          create: {
            locationId,
            timePeriod,
            level
          }
        })
      )
    );

    ResponseHelper.success(res, results, '批量更新成功');

  } catch (error: any) {
    console.error('批量更新拥堵程度失败:', error);
    ResponseHelper.serverError(res, '批量更新拥堵程度失败', error);
  }
};

/**
 * 删除地点某时段的拥堵程度
 * DELETE /api/v1/locations/:id/congestion/:timePeriod
 * 需要JWT认证和管理员权限
 */
export const deleteCongestionLevel = async (req: Request, res: Response): Promise<void> => {
  try {
    if (!req.user) {
      ResponseHelper.unauthorized(res, '请先登录');
      return;
    }

    if (req.user.role !== 'ADMIN') {
      ResponseHelper.forbidden(res, '仅管理员可删除拥堵程度');
      return;
    }

    const { id, timePeriod } = req.params;
    const locationId = parseInt(id, 10);

    if (isNaN(locationId)) {
      ResponseHelper.validationError(res, [
        { field: 'id', message: '无效的地点ID' }
      ]);
      return;
    }

    // 验证时段
    if (!['BREAKFAST', 'LUNCH', 'DINNER', 'OTHER'].includes(timePeriod as string)) {
      ResponseHelper.validationError(res, [
        { field: 'timePeriod', message: '无效的时段' }
      ]);
      return;
    }

    // 检查拥堵程度是否存在
    const existingCongestion = await prisma.congestionLevel.findUnique({
      where: {
        locationId_timePeriod: {
          locationId,
          timePeriod: timePeriod as TimePeriod
        }
      }
    });

    if (!existingCongestion) {
      ResponseHelper.notFound(res, '拥堵程度不存在');
      return;
    }

    // 删除拥堵程度
    await prisma.congestionLevel.delete({
      where: {
        locationId_timePeriod: {
          locationId,
          timePeriod: timePeriod as TimePeriod
        }
      }
    });

    ResponseHelper.success(res, null, '删除成功');

  } catch (error: any) {
    console.error('删除拥堵程度失败:', error);
    ResponseHelper.serverError(res, '删除拥堵程度失败', error);
  }
};
